import { reduce } from 'lodash';
import { option_datetimePicker } from './../../components/def-option.js'
import { CommonPicturePackage } from '../../assets/CommonPicturePackage.js';
import mixinsFun from './mixinsFun.vue';
export default {
  name: 'Create',
  mixins: [mixinsFun],
  components: {
    CusForm: () => { return import('./cusForm.vue'); },
    WxMsg: () => { return import('./../../components/wx_msgArea.vue'); },
  },
  computed: {
    // 一些变量在data里用缩写，computed用后端提交值
    eSCompanyId: function () { return this.esId; },//企业微信ID
    qYWXUsersId: function () { return this.cusId; },//企业微信客户ID
    Lo_MsgList: function () {
      let ls = this.L_MsgList;
      let rs = this.R_MsgList.map((v) => {
        return v.chatMsgId
      })
      let arr = ls.map((v) => {
        // console.log(v)
        return Object.assign(v, {
          isInRight: rs.includes(v.chatMsgId)
        })
      })
      return arr
    },
    // Lo_appList: function () {
    //   let ls = this.L_MsgList;
    //   let hash = {};
    //   return ls.reduce((t, v, i, a) => {
    //     hash[v.appId] ? '' : hash[v.appId] = true && t.push({
    //       value: v.appId, label: v.appName
    //     })
    //     return t;
    //   }, [{ value: 0, label: '--全应用平台--' }])
    // },
    Ro_MsgList: function () { return [] },

    chatMsgIdList: function () {
      if (this.R_MsgList.length == 0) {
        return '';
      } else {
        return this.R_MsgList.map((v) => {
          return v.chatMsgId
        }).join(',')
      }//消息列表（提交前转string类型，用','分隔ID）所以实际是string
    }
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      noAgent: CommonPicturePackage.noAgent,
      noData: CommonPicturePackage.noData,
      step: 0,//0:选人，1:编辑，2:提交
      datepicker: (() => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
        return [start, end]
      })(),
      pickerOptions: option_datetimePicker,
      ceId: (() => { return this.$store.getters.getCEID(true) })(),//员工ID
      esId: null,
      cusId: null,
      rfTitle: '',//标题
      L_MsgList: [],
      R_MsgList: [],
      L_loading: false,
      R_loading: false,
      selectAppValue: '',
    }
  },
  methods: {
    selectCus(cusObj) {
      this.esId = cusObj.eSCompanyId;
      this.cusId = cusObj.id;
      this.$emit('addTitle', cusObj.nickname);
      this.step = 1;
    },
    //选人步骤，步骤1，显性切换
    //根据被选人，加载历史记录，步骤2，隐性切换

    // getHistory(){}, // 调接口数据，清空当前数组，填充新数据，现迁移到mixinsFun中复用
    thisGetHistory() {
      if (this.datepicker === null || this.datepicker[0] === '' || this.datepicker[1] === '') {
        this.$message({
          type: 'warning',
          message: '请选择时间范围',
        })
        return
      }
      this.L_loading = true;
      this.getHistory(
        {
          eSCompanyId: this.esId,
          usersId: this.cusId,
          beginTime: this.$moment(this.datepicker[0]).format("YYYY-M-D H:m:s"),
          endTime: this.$moment(this.datepicker[1]).format("YYYY-M-D H:m:s"),
        },
        this.L_MsgList,
        () => { this.L_loading = false },
      )
    },
    selfChecking(action, msg) {
      let target = this.R_MsgList;
      let a = ((action) => {
        return { 'add': 1, 'remove': 2 }[action]
      })(action)// 1:添加消息 2:删除消息
      let idx = target.findIndex((v) => {
        return v.chatMsgId === msg.chatMsgId
      })//定位 被选消息 是否在左侧中
      if (a === 1 && idx >= 0) {
        this.$message({ type: 'warning', message: '请勿重复添加' })
        return true;
      }
      if (a === 2 && idx < -1) {
        this.$message({ type: 'warning', message: '该记录可能不存在' })
        return true;
      }
      return false;//false:没问题
    },// 自检左右移位的可行性

    selectAll2Right() {
      this.R_loading = true;
      let source = this.L_MsgList;
      let target = this.R_MsgList;
      // let $moment = this.$moment;
      target.splice(0, target.length)
      source.forEach((v) => {
        target.push(
          Object.assign(v, {
            esName: !v.isMe ? v.esName : v.appName
          })
        )
      })
      this.R_loading = false;
    },
    addMsg_R(msg) {
      console.log(msg)
      if (this.selfChecking('add', msg)) { return }
      let target = this.R_MsgList;
      target.push(
        Object.assign(msg, {
          esName: !msg.isMe ? msg.esName : msg.appName
        })
      );//先插入再排序
      this.sortMsg_R();
    },//将左侧列表的数据加入右侧列表，需去重及排序
    removeMsg_R(msg) {
      let target = this.R_MsgList;
      if (target.length < 2) {
        this.$message({
          type: 'warning',
          message: '最后一条记录',
        })
        return
      }//移除前判断
      let idx = target.findIndex((v) => {
        return v.chatMsgId === msg.chatMsgId
      })
      target.splice(idx, 1)
    },//将右侧列表的数据移除
    sortMsg_R() {
      let $moment = this.$moment;
      this.R_MsgList.sort((a, b) => {
        return $moment(a.addTime).isBefore(b.addTime) ? -1 : 1
      })
    },

    /*现在这些没用，但组件接口保留*/
    scroll(v) {
      if (v === "Top") { }
      return;
    },//滚动时处理函数，一般收到的参数是Top或Bottom
    /*现在这些没用，但组件接口保留*/


    submitNewRForms() {
      let arg = {
        companyEmployeeId: this.ceId,
        companyEmplyoeeId: this.ceId,
        eSCompanyId: this.eSCompanyId,
        qYWXUsersId: this.qYWXUsersId,
        title: this.rfTitle.trim(),
        chatMsgIdList: this.chatMsgIdList
      }
      // 验证参数
      if (_.isNull(arg.eSCompanyId) || _.isNull(arg.qYWXUsersId)) {
        return false;
      }
      if (arg.title === '') {
        this.$message({ type: 'error', message: '标题未填写', })
        return false
      }
      if (arg.chatMsgIdList.length < 1) {
        this.$message({ type: 'error', message: '记录为空', })
        return false
      }
      this.$api.postCreateReportForms(arg).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '提交成功',
          })
          this.$emit('submit2success')
        }
      }).catch((err) => {
        console.error(err)
      })
    },//提交
  },
  mounted() {

  }
}
